package me.shurufa.activities;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.litesuits.common.utils.MD5Util;

import butterknife.Bind;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.toolsfinal.coder.MD5Coder;
import me.shurufa.R;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.net.API;
import me.shurufa.net.RequestParams;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;

/**
 * 作者 : andy
 * 日期 : 16/3/14 14:19
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 重置密码 一步完成
 */
public class ResetPasswordGetCodeActivity extends BaseActivity implements View.OnClickListener {

    @Bind(R.id.mobile_edit)
    EditText mobileEdit;
    @Bind(R.id.verify_code_edit)
    EditText verifyCodeEdit;
    @Bind(R.id.left_text)
    TextView leftText;
    @Bind(R.id.right_text)
    TextView rightText;
    @Bind(R.id.verify_code_button)
    TextView verifyCodeButton;

    @Bind(R.id.password_edit)
    EditText password_edit;
    @Bind(R.id.confirm_password_edit)
    EditText confirm_password_edit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        activity_layout_res = R.layout.activity_reset_pwd_getcode;
        super.onCreate(savedInstanceState);
        initUI();
        initListener();
    }

    private void initUI() {
        titleTextView.setText(getString(R.string.reset_pwd));
        rightText.setVisibility(View.VISIBLE);
        rightText.setText(getString(R.string.complete));
        rightText.setOnClickListener(this);
    }

    private void initListener() {
        verifyCodeButton.setOnClickListener(this);
        rightText.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                reqResetPwd();
                break;
            case R.id.verify_code_button:
                if (mobileEdit.getText().toString().trim().length() == 11) {
                    getVerifyCode();
                } else {
                    Utils.showToast(R.string.input_valid_mobile_number);
                    mobileEdit.requestFocus();
                }
                break;
        }
    }

    /**
     * 请求设置密码
     */
    private void reqResetPwd() {

        // 校验
        final String newPwd = password_edit.getText().toString();
        final String confirmNewPwd = confirm_password_edit.getText().toString();
        final String verifyCode = verifyCodeEdit.getText().toString().trim();
        final String mobile= mobileEdit.getText().toString().trim();

        if (TextUtils.isEmpty(verifyCode)) {
            Utils.showToast(R.string.invalid_verify_code);
            verifyCodeEdit.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(mobile) || mobile.length() != 11) {
            Utils.showToast(R.string.input_valid_mobile_number);
            mobileEdit.requestFocus();
            return;
        }

        if (TextUtils.isEmpty(newPwd) || TextUtils.isEmpty(confirmNewPwd) || !confirmNewPwd.equals(newPwd)) {
            Utils.showToast(R.string.pwd_dont_match);
            return;
        }

        if (confirmNewPwd.length() < getResources().getInteger(R.integer.min_password_length)) {
            Utils.showToast(R.string.password_too_short);
            password_edit.requestFocus();
            return;
        }

        RequestParams params = new RequestParams();
        params.addFormDataPart("captcha", verifyCodeEdit.getText().toString().trim());
        params.addFormDataPart("mobile", mobileEdit.getText().toString().trim());
        params.addFormDataPart("password", MD5Coder.getMD5Code(newPwd));

        HttpRequest.post(API.RESET_PWD, params, new HttpCallback<BaseResp>(this) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    Utils.showToast(baseResp.message);
                    PersistenceUtils.logout();
                    finishToLogin();
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    private void finishToLogin() {
        Intent in = new Intent(this, NewLoginActivity.class);
        in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(in);
        finish();
    }

    private void onNext() {
        if (TextUtils.isEmpty(verifyCodeEdit.getText().toString())) {
            Utils.showToast(R.string.invalid_verify_code);
            return;
        }

        if (!Utils.isMobileNO(mobileEdit.getText().toString())) {
            Utils.showToast(R.string.please_input_mobile_number);
            return;
        }

        // 跳转 携带数据 验证码
        String code = verifyCodeEdit.getText().toString();
        String phone = mobileEdit.getText().toString();
        Intent in = new Intent(ResetPasswordGetCodeActivity.this, ResetPasswordSubmitActivity.class);
        ResetPasswordSubmitActivity.initArguments(in, code, phone);
        startActivity(in);
    }

    private void getVerifyCode() {
        /*final Map<String, Object> params = new HashMap<>();
        params.put("mobile", mobileEdit.getText().toString());
        params.put("type", "reset");

        if (!NetworkUtils.isNetAvailable(this)){
            Utils.showToast(R.string.network_error);
        }
        new RequestServerTask<BaseResponse>(BaseResponse.class, this, getString(R.string
                .getting_registration_sms)) {
            @Override
            protected String requestServer() {
                return HttpUtil.post(API.SEND_CAPTCHA, params);
            }

            @Override
            protected void onSuccess(BaseResponse result) {
                Utils.showToast(R.string.get_registration_sms_success);
                mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
                verifyCodeEdit.requestFocus();
            }

        }.setDefaultErrMsg(R.string.get_registration_sms_failed).start();*/

        RequestParams params = new RequestParams();
        params.addFormDataPart("mobile", mobileEdit.getText().toString());
        params.addFormDataPart("send_type", "find_password");

        HttpRequest.post(API.GET_CAPTCHA, params, new HttpCallback<BaseResp>(this) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    Utils.showToast(R.string.get_registration_sms_success);
                    mHandler.sendEmptyMessage(MSG_COUNT_DOWN_BEGIN);
                    verifyCodeEdit.requestFocus();
                } catch (Exception e) {
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    //    倒计时 start
    private static final int MSG_COUNT_DOWN = 30;

    private static final int MSG_COUNT_DOWN_BEGIN = 31;

    private static final int MSG_COUNT_DOWN_FINISHED = 32;

    private int countDown = Constants.SMS_COUNT_DOWN_TIME;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_COUNT_DOWN_BEGIN:
                    verifyCodeButton.setEnabled(false);
                    sendEmptyMessage(MSG_COUNT_DOWN);
                    break;
                case MSG_COUNT_DOWN:
                    countDown--;
                    verifyCodeButton.setText(
                            String.format(getString(R.string.count_down_time_left), countDown));
                    if (countDown > 0) {
                        sendEmptyMessageDelayed(MSG_COUNT_DOWN, 1000);
                    } else {
                        verifyCodeButton.setText(getString(R.string.get_verify_code));
                        verifyCodeButton.setEnabled(true);
                        countDown = Constants.SMS_COUNT_DOWN_TIME;
                    }
                    break;
                case MSG_COUNT_DOWN_FINISHED:
                    break;

            }

        }
    };

    private void finishCountdown() {
        countDown = 0;
        mHandler.removeMessages(MSG_COUNT_DOWN);
    }
//    倒计时 end

    @Override
    public void onDestroy() {
        finishCountdown();
        super.onDestroy();
    }
}
